package com.arges.controller;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CompletableFutureTest {
    //创建线程池,不建议使用该方法创建,本文主要是讲解CompletableFuture,线程池部分不详细介绍
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main方法开始。。。");
        long startTime = System.currentTimeMillis();
        //方法执行完成后的处理
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
            for (int j = 0; j < 10; j++) {
                System.out.println(j);
            }
            return i;
        }, executor).handle((res, exec) -> {
            if (res != null) {
                return res * 2;
            }
            if (exec != null) {
                return 0;
            }
            return 0;
        });
        //获取异步任务的返回值
        Integer integer = future.get();
        System.out.println("main方法结束。。。" + integer);
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);
    }
}
